package com.dog.basics.common.photooss.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.dog.basics.common.enums.QiniuZone;
import com.dog.basics.common.photooss.properties.QiniuOSSProperties;
import com.dog.basics.common.photooss.service.PhotoOssUtil;
import com.google.gson.Gson;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;
import java.util.Objects;

/**
 * @program: baby_singing_together
 *
 * @description: 七牛云上传
 *
 * @author: Guo
 *
 * @create: 2020-02-14 22:37
 **/
@Log4j2
public class QiniuPhotoOssUtil  implements PhotoOssUtil {


	/**
	 * 配置信息
	 */
	private QiniuOSSProperties qiniu;

	/**
	 * 构建一个七牛上传工具实例
	 */
	private UploadManager uploadManager;
	/**
	 * 认证信息实例
	 * @return
	 */
	private Auth auth;

	/**
	 * 构建七牛空间管理实例
	 */
	private BucketManager bucketManager;



	/**
	 * 初始化
	 * @param qiniu
	 */
	public  QiniuPhotoOssUtil(QiniuOSSProperties qiniu){
		this.qiniu = qiniu;
		this.uploadManager =  new UploadManager(qiniuConfig());
		this.auth =  Auth.create(qiniu.getAccessKey(), qiniu.getSecretKey());
		this.bucketManager = new BucketManager(auth, qiniuConfig());
		log.info("初始化七牛云OSS上传");
	}


	/**
	 * 根据配置文件选择机房
	 */
	private com.qiniu.storage.Configuration qiniuConfig() {
		Zone zone = null;
		if (Objects.equals(qiniu.getZone(), QiniuZone.HUA_BEI)) {
			zone = Zone.huabei();
		} else if (Objects.equals(qiniu.getZone(), QiniuZone.HUA_DONG)) {
			zone = Zone.huadong();
		} else if (Objects.equals(qiniu.getZone(), QiniuZone.HUA_NAN)) {
			zone = Zone.huanan();
		} else if (Objects.equals(qiniu.getZone(), QiniuZone.BEI_MEI)) {
			zone = Zone.beimei();
		} else if (Objects.equals(qiniu.getZone(), QiniuZone.XIN_JIA_PO)) {
			zone = Zone.xinjiapo();
		}
		return new com.qiniu.storage.Configuration(zone);
	}

	/**
	 * 获取上传凭证
	 *
	 * @return
	 */
	private String getUploadToken() {
		return this.auth.uploadToken(qiniu.getBucket());
	}

	/**
	 * @功能描述: byte文件流上传
	 * @author He
	 * @date 2020/3/1 18:46
	 * @Param: [read, bucketName, storagePath, prefix]
	 * @Return: java.lang.String
	 */
	@Override
	@SneakyThrows
	public String uploadFile(byte[] read, String bucketName, String storagePath, String prefix) {
		String suffix = StrUtil.isNotBlank(prefix)?StrUtil.format(".{}",prefix):FileTypeUtil.getType(IoUtil.toStream(read));
		String fileName = StrUtil.format("{}/{}{}",DateUtil.format(DateUtil.date(), "yyyy/MM/dd"),RandomUtil.randomUUID(),suffix);
		fileName =StrUtil.isNotBlank(storagePath)?StrUtil.format("{}/{}",storagePath,fileName):fileName;
		Response response = this.uploadManager.put(read, fileName, getUploadToken());
		int retry = 0;
		while (response.needRetry() && retry < 3) {
			response = this.uploadManager.put(read, fileName, getUploadToken());
			retry++;
		}
		//解析结果
		DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
		String return_path =   putRet.key;
		log.info("文件名称={}", return_path);
		return return_path;
	}

	/**
	 * @功能描述: 根据文件 inputstream 上传图片
	 * @author He
	 * @date 2020/2/29 19:45
	 * @Param: [inputStream, bucketName, storagePath, prefix]
	 * @Return: java.lang.String
	 */
	@Override
	@SneakyThrows
	public String uploadFile(InputStream inputStream, String bucketName, String storagePath, String prefix) {
		String suffix = StrUtil.isNotBlank(prefix)?StrUtil.format(".{}",prefix):FileTypeUtil.getType(inputStream);
		String fileName = StrUtil.format("{}/{}{}",DateUtil.format(DateUtil.date(), "yyyy/MM/dd"),RandomUtil.randomUUID(),suffix);
		fileName =StrUtil.isNotBlank(storagePath)?StrUtil.format("{}/{}",storagePath,fileName):fileName;
		Response response = this.uploadManager.put(inputStream, fileName, getUploadToken(), null, null);
		int retry = 0;
		while (response.needRetry() && retry < 3) {
			response = this.uploadManager.put(inputStream, null, getUploadToken(), null, null);
			retry++;
		}
		//解析结果
		DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
		String return_path =   putRet.key;
		log.info("文件名称={}", return_path);
		return return_path;
	}

	/**
	 * 上传文件
	 *
	 * @param files
	 * @param bucketName
	 * @param storagePath
	 * @return
	 * guonh 2020年2月6日
	 */
	@Override
	public List<String> uploadFile(MultipartFile[] files, String bucketName, String storagePath, String prefix) {
		return null;
	}

	/**
	 * 上传文件
	 *
	 * @param file
	 * @param bucketName
	 * @param storagePath
	 * @return
	 * guonh 2020年2月6日
	 */
	@Override
	@SneakyThrows
	public String uploadFile(MultipartFile file, String bucketName, String storagePath, String prefix) {
		String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		String fileName = StrUtil.format("{}/{}{}",DateUtil.format(DateUtil.date(), "yyyy/MM/dd"),RandomUtil.randomUUID(),suffix);
		fileName =StrUtil.isNotBlank(storagePath)?StrUtil.format("{}/{}",storagePath,fileName):fileName;
		InputStream inputStream = file.getInputStream();
		Response response = this.uploadManager.put(inputStream, fileName, getUploadToken(), null, null);
		int retry = 0;
		while (response.needRetry() && retry < 3) {
			response = this.uploadManager.put(inputStream, null, getUploadToken(), null, null);
			retry++;
		}
		//解析结果
		DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
		String return_path =   putRet.key;
		log.info("文件名称={}", return_path);
		return return_path;
	}


	/**
	 * 删除文件
	 *
	 * @param fileName
	 * @param bucketName
	 * guonh 2020年2月6日
	 */
	@Override
	@SneakyThrows
	public void deleteFile(String fileName, String bucketName) {
		Response response = bucketManager.delete(qiniu.getBucket(), fileName);
		int retry = 0;
		while (response.needRetry() && retry++ < 3) {
			response = bucketManager.delete(qiniu.getBucket(), fileName);
		}
	}


	/**
	 * 根据图片全路径删除就图片
	 *
	 * @param imgUrl     图片全路径
	 * @param bucketName 存储路径
	 * guonh 2020年2月6日
	 */
	@Override
	public void delImg(String imgUrl, String bucketName) {

	}

	/**
	 * 判断文件是否存在
	 *
	 * @param fileName   文件名称
	 * @param bucketName 文件储存空间名称
	 * @return true:存在,false:不存在
	 * guonh 2020年2月6日
	 */
	@Override
	public boolean doesObjectExist(String fileName, String bucketName) {
		return false;
	}


	/**
	 * 复制文件
	 *
	 * @param fileName              源文件名称
	 * @param bucketName            源储存空间名称
	 * @param destinationBucketName 目标储存空间名称
	 * @param destinationObjectName 目标文件名称
	 *  guonh 2020年2月6日
	 */
	@Override
	public void ossCopyObject(String fileName, String bucketName, String destinationBucketName,
			String destinationObjectName) {

	}
}
